package com.rongshu.view.penpal.present;

import android.content.Context;
import android.text.TextUtils;

import com.rongshu.R;
import com.rongshu.api.RetorfitService;
import com.rongshu.utils.Common;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.BasePresenter;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.discovery.bean.AuthorDetailBean;
import com.rongshu.view.home.entity.ArticleLike;
import com.rongshu.view.home.entity.CommenOneAllDetails;
import com.rongshu.view.home.entity.CommentDetails;
import com.rongshu.view.home.entity.CommentReplysBean;
import com.rongshu.view.penpal.bean.PostCommentBody;
import com.rongshu.view.penpal.bean.PostDetailsResponse;
import com.rongshu.view.penpal.view.PostDetailsView;
import com.utils.LogUtil;
import com.utils.StringUtils;
import com.widget.toast.ToastUtils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Func1;

/**
 * created by zhengweis on 2018/12/4.
 * description：
 */
public class PostDetailsPresenter extends BasePresenter<PostDetailsView> {
    BaseActivity activity = (BaseActivity) mContext;

    public PostDetailsPresenter(Context context) {
        super(context);
    }

    public void getPostDetails(int postId) {
        activity.showLoading(true);
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("topic_id", postId);
        RetorfitService.postDetails(UserInfoUtils.getUserId(), postId,
                Common.encryptionSign(map))
                .compose(getView().<PostDetailsResponse>bindToLife()).doOnSubscribe(new Action0() {
            @Override
            public void call() {

            }
        }).subscribe(new Subscriber<PostDetailsResponse>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(PostDetailsResponse object) {
                getView().onPostMsg(object);
            }
        });
    }


    public void ConcernWith(int user_id_to) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("contribute_id", 0);
        map.put("user_id_to", user_id_to);
        RetorfitService.ConcernWith(UserInfoUtils.getUserId(), 0, user_id_to,
                Common.encryptionSign(map))
                .compose(getView().<INetBean>bindToLife()).doOnSubscribe(new Action0() {
            @Override
            public void call() {

            }
        }).subscribe(new Subscriber<INetBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(INetBean object) {
                ToastUtils.show(mContext.getString(R.string.add_attention_success));
            }
        });
    }

    /**
     * 获取文章详情下的评论
     */
    public void getCommentDetail(int topic_id, int Sort,
                                 int pageIndex, int pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("topic_id", topic_id);
        map.put("Sort", Sort);
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        RetorfitService.getPostCommentDetail(UserInfoUtils.getUserId(), topic_id, Sort, pageIndex, pageSize, Common.encryptionSign(map))
                .map(new Func1<CommentDetails, List<CommentDetails.ResponseBean>>() {
                    @Override
                    public List<CommentDetails.ResponseBean> call(CommentDetails commentDetails) {
                        return commentDetails.getResponse();
                    }
                })
                .compose(getView().<List<CommentDetails.ResponseBean>>bindToLife())
                .subscribe(new Subscriber<List<CommentDetails.ResponseBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<CommentDetails.ResponseBean> responseBeanList) {
                        if (responseBeanList != null) {
                            getView().onCommentMsg(responseBeanList);
                        }
                    }
                });
    }

    /**
     * 文章点赞/帖子点赞
     */
    public void getlike(int id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("type", "post");//点赞类型(post帖子，article文章)
        RetorfitService.getlike(id, UserInfoUtils.getUserId(), "post", Common.encryptionSign(map))
                .compose(getView().<ArticleLike>bindToLife())
                .subscribe(new Subscriber<ArticleLike>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ArticleLike articleLike) {
                        if (articleLike.getErrCode() == 0) {
                            getView().onPostList();
                        } else {
                            ToastUtils.show(articleLike.getErrMsg());
                        }
                    }
                });
    }

    /**
     * 取消帖子点赞
     */
    public void getOfflike(int contribute_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("type", "post");//点赞类型(post帖子，article文章)
        map.put("contribute_id", contribute_id);//点赞类型(post帖子，article文章)
        RetorfitService.getOfflike(UserInfoUtils.getUserId(), "post", contribute_id, Common.encryptionSign(map))
                .compose(getView().<ArticleLike>bindToLife())
                .subscribe(new Subscriber<ArticleLike>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ArticleLike articleLike) {
                        if (getView() != null) {
                            getView().onPostList();
                        }
                    }
                });
    }

    public void postComment(LinkedHashMap<String, AuthorDetailBean> authorDetailBeanMap, int penpalId,
                            int postId, int commentId, int replyId, String content) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("penpalwill_id", penpalId);
        map.put("topic_id", postId);
        map.put("comment_id", commentId);
        map.put("reply_id", replyId);
        PostCommentBody body = new PostCommentBody();
        body.setContents(content);
        StringBuilder aiteStrsb = new StringBuilder();
        for (Map.Entry<String, AuthorDetailBean> entry : authorDetailBeanMap.entrySet()) {
            aiteStrsb.append(entry.getValue().getUser_id_to());
        }
        body.setAiteStr(aiteStrsb.toString());
        RetorfitService.postComment(UserInfoUtils.getUserId(), penpalId, postId, commentId, replyId,
                Common.encryptionSign(map), body)
                .compose(getView().<ResponseBody>bindToLife())
                .subscribe(new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        getView().commentSuccess(responseBody);
                    }
                });
    }

    /**
     * 获取单个评论下的所有回复
     */
    public void getOnecommentDetail(int comment_id, int pageIndex, int pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("comment_id", comment_id);
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        RetorfitService.getOnecommentDetail(UserInfoUtils.getUserId(), comment_id, pageIndex, pageSize, Common.encryptionSign(map))
                .map(new Func1<CommenOneAllDetails, List<CommentReplysBean>>() {
                    @Override
                    public List<CommentReplysBean> call(CommenOneAllDetails commenOneAllDetails) {
                        return commenOneAllDetails.getComment_replys();
                    }
                })
                .map(new Func1<List<CommentReplysBean>, List<CommentReplysBean>>() {
                    @Override
                    public List<CommentReplysBean> call(List<CommentReplysBean> commentReplysBeans) {
                        for (CommentReplysBean commentReplysBean : commentReplysBeans) {
                            commentReplysBean.setAvatar(commentReplysBean.getFrom_avatar());
                            commentReplysBean.setVip(commentReplysBean.isFrom_vip());
                        }
                        return commentReplysBeans;
                    }
                })
                .compose(getView().<List<CommentReplysBean>>bindToLife())
                .subscribe(new Subscriber<List<CommentReplysBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<CommentReplysBean> commentReplysBeans) {
                        getView().onOnecommentDetail(commentReplysBeans);
                    }
                });
    }

    /**
     * 评论点赞（任何评论）
     */
    public void getCommentlike(int obj_id, int comment_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("type", 2);
        map.put("obj_id", obj_id);
        map.put("comment_id", comment_id);
        RetorfitService.getCommentlike(UserInfoUtils.getUserId(), 2, obj_id, comment_id, Common.encryptionSign(map))
                .compose(getView().<INetBean>bindToLife())
                .subscribe(new Subscriber<INetBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(INetBean iNetBean) {
                        if (iNetBean.getErrCode() != 0) {
                            ToastUtils.show(iNetBean.getErrMsg());
                        } else {
                            getView().onCommentlike();
                        }
                    }
                });
    }

    private Disposable disposable;

    /**
     * 处理文章内容
     *
     * @param html
     */
    public void dealWithContent(final String html) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) {
                List<String> textList = StringUtils.cutStringByImgTag(html);
                for (int i = 0; i < textList.size(); i++) {
                    String text = textList.get(i);
                    emitter.onNext(text);
                }
            }
        })
                .subscribeOn(Schedulers.io())//生产事件在io
                .observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
                .subscribe(new Observer<String>() {
                    @Override
                    public void onComplete() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.show("解析错误：图片不存在或已损坏");
                        LogUtil.e("onError: " + e.getMessage());
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(String text) {
                        getView().onCallBackDealWithContent(text);

                    }
                });
    }

    /**
     * 帖子评论删除/帖子回复删除
     */
    public void postDeleteComment(int topic_id, int comment_id, int reply_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfoUtils.getUserId());
        map.put("topic_id", topic_id);
        map.put("comment_id", comment_id);
        map.put("reply_id", reply_id);
        RetorfitService.postDeleteComment(UserInfoUtils.getUserId(), topic_id, comment_id, reply_id, Common.encryptionSign(map))
                .compose(getView().<INetBean>bindToLife())
                .subscribe(new Subscriber<INetBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(INetBean bean) {
                        getView().onCommentDelete(bean);
                    }
                });
    }


    public void onDestory() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }
}
